package com.barrett.hvzmoderator.com.barrett;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.alexd.jsonrpc.JSONRPCClient;
import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;

import com.barrett.hvzmoderator.R;

public class hvzachievements extends Activity {
	
    
    private ProgressDialog load;
    private ProgressDialog click;
    private ListView achievementList;
    private ArrayList<String> Achievements = new ArrayList<String>();
    private ArrayList<Achievement> achIndex = new ArrayList<Achievement>();
    private ArrayList<Integer> bidIndex = new ArrayList<Integer>();
    
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ach);
        
        
        
        
        final ListView achList = (ListView) findViewById(R.id.achList);
        achList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        achList.setSaveEnabled(true);
        achList.setTextFilterEnabled(true);
        
        achievementList = (ListView) findViewById(R.id.achList);
        achievementList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        achievementList.setSaveEnabled(true);
        achievementList.setTextFilterEnabled(true);
        
        
        final String sessid = getIntent().getStringExtra("sessid");
        final int uid = getIntent().getIntExtra("uid",0);
        
        click = new ProgressDialog(this);
        click.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        click.setMessage("Loading...");
        click.setCancelable(false);
        
        load = new ProgressDialog(this);
		load.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		load.setMessage("Loading...");
		load.setCancelable(false);
        load.show();
        
        achList.setOnItemLongClickListener(new OnItemLongClickListener(){

        	@Override
        	public boolean onItemLongClick(AdapterView<?> parent, View view,
        			int position, long id) {
        		// TODO Auto-generated method stub
        		Achievement ach = achIndex.get(position);

        		BitmapDrawable bm = null;
        		try {
        			/* Open a new URL and get the InputStream to load data from it. */
        			URL aURL = new URL(ach.pic);
        			URLConnection conn = aURL.openConnection();
        			conn.connect();
        			InputStream is = conn.getInputStream();
        			/* Buffered is always good for a performance plus. */
        			BufferedInputStream bis = new BufferedInputStream(is);
        			/* Decode url-data to a bitmap. */
        			bm = new BitmapDrawable(BitmapFactory.decodeStream(bis));
        			bis.close();
        			is.close();
        			/* Apply the Bitmap to the ImageView that will be returned. */
        		} catch (IOException e) {
        			Log.e("DEBUGTAG", "Remtoe Image Exception", e);
        		}




        		
        		AlertDialog.Builder builder = new AlertDialog.Builder(parent.getContext());
        		builder.setTitle(ach.name)
        		.setMessage("Points: " + Integer.toString(ach.points))
        		.setIcon(bm)
        		.setCancelable(true)
        		.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
        			public void onClick(DialogInterface dialog, int id) {
        				dialog.dismiss();
        			}
        		});
        		AlertDialog alert = builder.create();
        		alert.show();
        		return false;
        	}

        });
        
        achList.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> l, final View v, final int position, long id) {
				click.show();
				CheckedTextView textView = (CheckedTextView)v;
				textView.setChecked(!textView.isChecked());
				final Achievement ach = achIndex.get(position);
				ach.obtained = !ach.obtained;
				
				
				final Thread Click = new Thread() {
					
					final String sessid = getIntent().getStringExtra("sessid");
			        final String uid = Integer.toString(getIntent().getIntExtra("uid", 0));		
			        
					public void run() {
						
						Message msg1 = new Message();
	                	Bundle b1 = new Bundle();
	                	b1.putBoolean("start", true);
	    				msg1.setData(b1);
	    				clickHandler.sendMessage(msg1);
						
						JSONRPCClient client = JSONRPCClient.create("http://www.ohiostateugc.com/services/json-rpc");
						String error = "";
						String output = "";
						try {
							
							if (achievementList.isItemChecked(position)) {
								boolean result = client.callBoolean("hvz.ach.add", sessid, uid, ach.bid);
								output = "Achievement Unlocked";
							}
							else {
								boolean result = client.callBoolean("hvz.ach.del", sessid, uid, ach.bid);
								output = "Achievement Re - locked";
							}

							Message msg2 = new Message();
		                	Bundle b2 = new Bundle();
		                	b2.putBoolean("win", true);
		                	b2.putString("output", output);
		    				msg2.setData(b2);
		    				clickHandler.sendMessage(msg2);
		    				

						} catch (JSONRPCException e) {
							// TODO Auto-generated catch block
							error = e.toString(); 
							Message msg2 = new Message();
		                	Bundle b2 = new Bundle();
		                	b2.putBoolean("win", false);
		                	b2.putString("error", error);
		    				msg1.setData(b2);
		    				clickHandler.sendMessage(msg2);
						}
					}
				};
				Click.start();

			}
        	
        });

        Thread populateList = new Thread() {
			public void run() {
				int [] obtained = new int[100];
				try {
					JSONRPCClient client = JSONRPCClient.create("http://www.ohiostateugc.com/services/json-rpc");
					
					JSONArray check = client.callJSONArray("hvz.ach.get", sessid, uid);
            		JSONArray all = client.callJSONArray("hvz.ach.getall", sessid);
					
					//Log.v("hvz", "Max " + result.length());
					//dialog.setMax(result.length());
					//Log.v("hvz", "Max " + result.length());
					ArrayList<Integer> chk = new ArrayList<Integer>();
					
					for(int i = 0; i < check.length(); i++) {
						JSONObject obj = check.getJSONObject(i);
						chk.add(obj.getInt("bid"));
					}
					int achObt = 0;
					for(int i = 0; i < all.length(); i++) {

						Boolean ob = false;
						JSONObject achObj = all.getJSONObject(i);
						Integer bid = achObj.getInt("bid");
						if (chk.contains(bid)) {
							ob = true;
							obtained[achObt] = bid;
							achObt++;
						}
						
						Achievement ach = new Achievement(achObj.getInt("bid"),
								achObj.getString("name"),
								achObj.getInt("points"),
								achObj.getString("url"),
								ob
								); 
						
						achIndex.add(i, ach);
						bidIndex.add(i, bid);
						Achievements.add(i, ach.name);
						
						boolean t = false;
						t=!t;
					}
					obtained[achObt] = -1;
					
					
				} catch (Exception e) {
					Log.v("hvz", "EX" + e.toString());
					Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
				}
				
				Message msg1 = new Message();
            	Bundle b1 = new Bundle();
            	b1.putBoolean("win", true);
            	b1.putIntArray("obtained", obtained);
				msg1.setData(b1);
				listHandler.sendMessage(msg1);
			}
		};
        
        populateList.start();
         
	}
	
	
	private Handler listHandler = new Handler() {
		@Override
	      public void handleMessage(Message msg) {  
	    	  Bundle b = msg.getData();
	    	  
	    	  if (b.getBoolean("win")) {
	    		  load.dismiss();
	    		  achievementList.setAdapter(new ArrayAdapter<String>(getBaseContext(),
	    				  android.R.layout.simple_list_item_checked , 
	    				  Achievements));
	    		  int [] obt = b.getIntArray("obtained");
	    		  for(int i = 0; i < obt.length; i++) {
	    			  if (obt[i] == -1) continue;
	    			  
	    			  achievementList.setItemChecked(bidIndex.indexOf(obt[i]), true);
	    		  }
	    		  achievementList.setEnabled(true);
	    		  Toast.makeText(getApplicationContext(), "Long Press for more info", Toast.LENGTH_SHORT).show();
	    	  }
	    	  
		}
	};
	
	
	private Handler clickHandler = new Handler () {
		@Override
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			if (b.getBoolean("start")) {
				//click.show();
			}
			else if (b.getBoolean("win")) {
				if (b.getBoolean("add")) {
					Toast.makeText(getApplicationContext(), b.getString("output"), Toast.LENGTH_SHORT).show();
				}
				else {
					Toast.makeText(getApplicationContext(), b.getString("output"), Toast.LENGTH_SHORT).show();
				}
				click.dismiss();
			}
			else {
				Toast.makeText(getApplicationContext(), "Error " + b.getString("error"), Toast.LENGTH_SHORT).show();
				click.dismiss();
			}
				
		}
	};
}
